<template>
  <view class="visitor-page">
    <!-- 页面头部 -->
    <view class="page-header">
      <view class="header-title">
        <u-icon name="arrow-left" size="20" color="#333" @click="goBack"></u-icon>
        <text class="title-text">访客管理</text>
      </view>
      <view class="header-actions">
        <u-button 
          type="primary" 
          size="small" 
          text="访客登记" 
          @click="showVisitorForm = true"
        ></u-button>
      </view>
    </view>

    <!-- 统计信息 -->
    <view class="stats-section">
      <view class="stat-card">
        <view class="stat-number">{{ visitorStats.total }}</view>
        <view class="stat-label">总访客数</view>
      </view>
      <view class="stat-card">
        <view class="stat-number">{{ visitorStats.pending }}</view>
        <view class="stat-label">待审核</view>
      </view>
      <view class="stat-card">
        <view class="stat-number">{{ visitorStats.active }}</view>
        <view class="stat-label">在小区内</view>
      </view>
    </view>

    <!-- 筛选区域 -->
    <view class="filter-section">
      <u-input
        v-model="searchKeyword"
        placeholder="搜索访客姓名或手机号"
        prefix-icon="search"
        clearable
        @input="handleSearch"
      ></u-input>
      <u-picker
        :show="showStatusPicker"
        :columns="[statusOptions]"
        @confirm="onStatusConfirm"
        @cancel="showStatusPicker = false"
      ></u-picker>
      <u-button 
        type="info" 
        size="small" 
        text="状态筛选" 
        @click="showStatusPicker = true"
      ></u-button>
    </view>

    <!-- 访客列表 -->
    <scroll-view 
      scroll-y="true" 
      class="visitor-list"
      :style="{ height: scrollViewHeight }"
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <view class="list-content">
        <view 
          v-for="visitor in filteredVisitors" 
          :key="visitor.id"
          class="visitor-card"
          @click="viewVisitorDetail(visitor)"
        >
          <view class="visitor-avatar">
            <u-avatar 
              :src="visitor.avatar" 
              size="50"
              :text="visitor.name.charAt(0)"
            ></u-avatar>
          </view>
          <view class="visitor-info">
            <view class="visitor-name">{{ visitor.name }}</view>
            <view class="visitor-phone">{{ visitor.phone }}</view>
            <view class="visitor-purpose">目的：{{ visitor.purpose }}</view>
            <view class="visitor-time">来访时间：{{ visitor.visitTime }}</view>
          </view>
          <view class="visitor-status">
            <u-tag 
              :text="visitor.statusText" 
              :type="getStatusType(visitor.status)"
              size="small"
            ></u-tag>
            <view class="visitor-action">
              <u-button 
                v-if="visitor.status === 'pending'"
                type="success" 
                size="mini" 
                text="审核通过" 
                @click.stop="approveVisitor(visitor)"
              ></u-button>
              <u-button 
                v-if="visitor.status === 'pending'"
                type="error" 
                size="mini" 
                text="拒绝" 
                @click.stop="rejectVisitor(visitor)"
              ></u-button>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 访客登记弹窗 -->
    <u-popup 
      :show="showVisitorForm" 
      mode="center" 
      :round="10"
      @close="showVisitorForm = false"
    >
      <view class="visitor-form-popup">
        <view class="popup-header">
          <text class="popup-title">访客登记</text>
          <u-icon name="close" size="20" @click="showVisitorForm = false"></u-icon>
        </view>
        <view class="popup-content">
          <u-form :model="visitorForm" ref="visitorFormRef">
            <u-form-item label="访客姓名" prop="name">
              <u-input v-model="visitorForm.name" placeholder="请输入访客姓名"></u-input>
            </u-form-item>
            <u-form-item label="手机号码" prop="phone">
              <u-input v-model="visitorForm.phone" placeholder="请输入手机号码" type="number"></u-input>
            </u-form-item>
            <u-form-item label="来访目的" prop="purpose">
              <u-input v-model="visitorForm.purpose" placeholder="请输入来访目的"></u-input>
            </u-form-item>
            <u-form-item label="来访时间" prop="visitTime">
              <u-input v-model="visitorForm.visitTime" placeholder="请选择来访时间" readonly @click="showTimePicker = true"></u-input>
            </u-form-item>
            <u-form-item label="预计离开" prop="leaveTime">
              <u-input v-model="visitorForm.leaveTime" placeholder="请选择预计离开时间" readonly @click="showLeaveTimePicker = true"></u-input>
            </u-form-item>
            <u-form-item label="备注" prop="remark">
              <u-textarea v-model="visitorForm.remark" placeholder="请输入备注信息"></u-textarea>
            </u-form-item>
          </u-form>
        </view>
        <view class="popup-actions">
          <u-button type="info" text="取消" @click="showVisitorForm = false"></u-button>
          <u-button type="primary" text="提交" @click="submitVisitorForm"></u-button>
        </view>
      </view>
    </u-popup>

    <!-- 时间选择器 -->
    <u-picker
      :show="showTimePicker"
      mode="time"
      @confirm="onTimeConfirm"
      @cancel="showTimePicker = false"
    ></u-picker>
    <u-picker
      :show="showLeaveTimePicker"
      mode="time"
      @confirm="onLeaveTimeConfirm"
      @cancel="showLeaveTimePicker = false"
    ></u-picker>
  </view>
</template>

<script setup>
/**
 * 访客管理页面
 * @author Wu.Liang
 * @date 2025-01-30
 * @version 1.0.0
 * @description 访客管理功能，包含访客列表、登记、审核等
 */

import { ref, reactive, computed, onMounted, nextTick } from 'vue'

// 页面状态
const showVisitorForm = ref(false)
const showStatusPicker = ref(false)
const showTimePicker = ref(false)
const showLeaveTimePicker = ref(false)
const refreshing = ref(false)
const searchKeyword = ref('')
const selectedStatus = ref('')

// 访客表单数据
const visitorForm = reactive({
  name: '',
  phone: '',
  purpose: '',
  visitTime: '',
  leaveTime: '',
  remark: ''
})

// 访客状态选项
const statusOptions = [
  { label: '全部状态', value: '' },
  { label: '待审核', value: 'pending' },
  { label: '已通过', value: 'approved' },
  { label: '已拒绝', value: 'rejected' },
  { label: '在小区内', value: 'active' },
  { label: '已离开', value: 'left' }
]

// 访客统计数据
const visitorStats = reactive({
  total: 0,
  pending: 0,
  active: 0
})

// 访客列表数据（演示数据）
const visitors = ref([
  {
    id: 1,
    name: '张三',
    phone: '138****1234',
    avatar: '',
    purpose: '探亲访友',
    visitTime: '2025-01-30 14:30',
    leaveTime: '2025-01-30 18:00',
    status: 'active',
    statusText: '在小区内',
    remark: '看望父母',
    createTime: '2025-01-30 14:00'
  },
  {
    id: 2,
    name: '李四',
    phone: '139****5678',
    avatar: '',
    purpose: '快递配送',
    visitTime: '2025-01-30 16:00',
    leaveTime: '2025-01-30 16:30',
    status: 'left',
    statusText: '已离开',
    remark: '顺丰快递',
    createTime: '2025-01-30 15:45'
  },
  {
    id: 3,
    name: '王五',
    phone: '137****9012',
    avatar: '',
    purpose: '装修施工',
    visitTime: '2025-01-30 09:00',
    leaveTime: '2025-01-30 17:00',
    status: 'active',
    statusText: '在小区内',
    remark: '3栋2单元装修',
    createTime: '2025-01-30 08:30'
  },
  {
    id: 4,
    name: '赵六',
    phone: '136****3456',
    avatar: '',
    purpose: '朋友聚会',
    visitTime: '2025-01-30 19:00',
    leaveTime: '2025-01-30 22:00',
    status: 'pending',
    statusText: '待审核',
    remark: '参加生日聚会',
    createTime: '2025-01-30 18:30'
  },
  {
    id: 5,
    name: '孙七',
    phone: '135****7890',
    avatar: '',
    purpose: '家政服务',
    visitTime: '2025-01-30 10:00',
    leaveTime: '2025-01-30 12:00',
    status: 'approved',
    statusText: '已通过',
    remark: '定期保洁服务',
    createTime: '2025-01-30 09:30'
  }
])

// 计算属性
const filteredVisitors = computed(() => {
  let result = visitors.value

  // 关键词搜索
  if (searchKeyword.value) {
    result = result.filter(visitor => 
      visitor.name.includes(searchKeyword.value) || 
      visitor.phone.includes(searchKeyword.value)
    )
  }

  // 状态筛选
  if (selectedStatus.value) {
    result = result.filter(visitor => visitor.status === selectedStatus.value)
  }

  return result
})

// 滚动视图高度
const scrollViewHeight = computed(() => {
  // 计算可用高度：屏幕高度 - 头部高度 - 统计区域高度 - 筛选区域高度 - 底部安全区域
  return 'calc(100vh - 200px)'
})

// 方法
const goBack = () => {
  uni.navigateBack()
}

const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

const onStatusConfirm = (event) => {
  selectedStatus.value = event.value[0]
  showStatusPicker.value = false
}

const getStatusType = (status) => {
  const statusMap = {
    pending: 'warning',
    approved: 'success',
    rejected: 'error',
    active: 'primary',
    left: 'info'
  }
  return statusMap[status] || 'info'
}

const viewVisitorDetail = (visitor) => {
  // 查看访客详情
  uni.showModal({
    title: '访客详情',
    content: `姓名：${visitor.name}\n手机：${visitor.phone}\n目的：${visitor.purpose}\n来访时间：${visitor.visitTime}\n状态：${visitor.statusText}`,
    showCancel: false
  })
}

const approveVisitor = (visitor) => {
  uni.showModal({
    title: '审核确认',
    content: `确定通过访客"${visitor.name}"的申请吗？`,
    success: (res) => {
      if (res.confirm) {
        visitor.status = 'approved'
        visitor.statusText = '已通过'
        updateVisitorStats()
        uni.showToast({
          title: '审核通过',
          icon: 'success'
        })
      }
    }
  })
}

const rejectVisitor = (visitor) => {
  uni.showModal({
    title: '拒绝确认',
    content: `确定拒绝访客"${visitor.name}"的申请吗？`,
    success: (res) => {
      if (res.confirm) {
        visitor.status = 'rejected'
        visitor.statusText = '已拒绝'
        updateVisitorStats()
        uni.showToast({
          title: '已拒绝',
          icon: 'success'
        })
      }
    }
  })
}

const onTimeConfirm = (event) => {
  visitorForm.visitTime = `${event.year}-${event.month}-${event.day} ${event.hour}:${event.minute}`
  showTimePicker.value = false
}

const onLeaveTimeConfirm = (event) => {
  visitorForm.leaveTime = `${event.year}-${event.month}-${event.day} ${event.hour}:${event.minute}`
  showLeaveTimePicker.value = false
}

const submitVisitorForm = () => {
  // 表单验证
  if (!visitorForm.name || !visitorForm.phone || !visitorForm.purpose) {
    uni.showToast({
      title: '请填写完整信息',
      icon: 'none'
    })
    return
  }

  // 创建新访客记录
  const newVisitor = {
    id: Date.now(),
    name: visitorForm.name,
    phone: visitorForm.phone,
    avatar: '',
    purpose: visitorForm.purpose,
    visitTime: visitorForm.visitTime,
    leaveTime: visitorForm.leaveTime,
    status: 'pending',
    statusText: '待审核',
    remark: visitorForm.remark,
    createTime: new Date().toLocaleString()
  }

  // 添加到列表
  visitors.value.unshift(newVisitor)
  
  // 更新统计
  updateVisitorStats()
  
  // 重置表单
  Object.assign(visitorForm, {
    name: '',
    phone: '',
    purpose: '',
    visitTime: '',
    leaveTime: '',
    remark: ''
  })
  
  // 关闭弹窗
  showVisitorForm.value = false
  
  // 显示成功提示
  uni.showToast({
    title: '访客登记成功',
    icon: 'success'
  })
}

const updateVisitorStats = () => {
  visitorStats.total = visitors.value.length
  visitorStats.pending = visitors.value.filter(v => v.status === 'pending').length
  visitorStats.active = visitors.value.filter(v => v.status === 'active').length
}

const loadMore = () => {
  // 加载更多数据
  console.log('加载更多访客数据')
}

const onRefresh = () => {
  refreshing.value = true
  // 模拟刷新
  setTimeout(() => {
    refreshing.value = false
    uni.showToast({
      title: '刷新成功',
      icon: 'success'
    })
  }, 1000)
}

// 页面加载
onMounted(() => {
  updateVisitorStats()
})
</script>

<style lang="scss" scoped>
.visitor-page {
  min-height: 100vh;
  width: 100vw;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.page-header {
  background: white;
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
  
  .header-title {
    display: flex;
    align-items: center;
    gap: 12px;
    
    .title-text {
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }
  }
}

.stats-section {
  background: white;
  padding: 16px;
  display: flex;
  gap: 12px;
  margin-bottom: 12px;
  
  .stat-card {
    flex: 1;
    text-align: center;
    padding: 16px;
    background: #f8f9fa;
    border-radius: 8px;
    
    .stat-number {
      font-size: 24px;
      font-weight: 600;
      color: #3742fa;
      margin-bottom: 4px;
    }
    
    .stat-label {
      font-size: 12px;
      color: #666;
    }
  }
}

.filter-section {
  background: white;
  padding: 16px;
  display: flex;
  gap: 12px;
  align-items: center;
  margin-bottom: 12px;
  
  .u-input {
    flex: 1;
  }
}

.visitor-list {
  flex: 1;
  
  .list-content {
    padding: 16px;
  }
}

.visitor-card {
  background: white;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 12px;
  display: flex;
  align-items: flex-start;
  gap: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  
  .visitor-avatar {
    flex-shrink: 0;
  }
  
  .visitor-info {
    flex: 1;
    min-width: 0;
    
    .visitor-name {
      font-size: 16px;
      font-weight: 600;
      color: #333;
      margin-bottom: 4px;
    }
    
    .visitor-phone {
      font-size: 14px;
      color: #666;
      margin-bottom: 4px;
    }
    
    .visitor-purpose {
      font-size: 14px;
      color: #666;
      margin-bottom: 4px;
    }
    
    .visitor-time {
      font-size: 12px;
      color: #999;
    }
  }
  
  .visitor-status {
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    gap: 8px;
    
    .visitor-action {
      display: flex;
      gap: 8px;
    }
  }
}

.visitor-form-popup {
  width: 90vw;
  max-width: 400px;
  background: white;
  border-radius: 12px;
  overflow: hidden;
  
  .popup-header {
    padding: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #f0f0f0;
    
    .popup-title {
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }
  }
  
  .popup-content {
    padding: 20px;
    max-height: 60vh;
    overflow-y: auto;
  }
  
  .popup-actions {
    padding: 20px;
    display: flex;
    gap: 12px;
    border-top: 1px solid #f0f0f0;
    
    .u-button {
      flex: 1;
    }
  }
}

// 响应式适配
@media screen and (max-width: 375px) {
  .page-header {
    padding: 12px;
  }
  
  .stats-section {
    padding: 12px;
    
    .stat-card {
      padding: 12px;
      
      .stat-number {
        font-size: 20px;
      }
    }
  }
  
  .filter-section {
    padding: 12px;
  }
  
  .visitor-card {
    padding: 12px;
    gap: 12px;
  }
}

@media screen and (min-width: 414px) {
  .visitor-page {
    width: 100vw;
    max-width: none;
    margin: 0;
  }
}
</style> 